package c2.cross.business.minecraft.core;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import easy.java.dev.note.NoteClass;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static cate.game.pvp.minecraft.MinecraftManager.MODULE_NAME;

@NoteClass("灵能矿洞-时间轮")
public class MinecraftWheelManager {

    private final HashedWheelTimer timer;
    private final Map<String, Timeout> timerMap = Maps.newConcurrentMap();

    public MinecraftWheelManager() {
        this.timer = new HashedWheelTimer(new ThreadFactoryBuilder().setNameFormat(MODULE_NAME + "-%d").build());
    }

    public void startUp() {
        this.timer.start();
    }

    public void shutDown() {
        Set<Timeout> unprocessedTimeouts = this.timer.stop();
        if (!CollectionUtils.isEmpty(unprocessedTimeouts)) {
            unprocessedTimeouts.forEach(Timeout::cancel);
        }
    }

    public void createTimer(String token, long seconds, Runnable task) {
        Timeout timeout = this.timer.newTimeout(to -> {
            if (to.isExpired() || to.isCancelled()) {
                task.run();
            }
        }, seconds, TimeUnit.SECONDS);
        this.timerMap.put(token, timeout);
    }

    public void removeTimer(String token) {
        Optional.ofNullable(this.timerMap.remove(token))
                .ifPresent(Timeout::cancel);
    }
}
